package com.xysq.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.rockcent.action.CallbackListener;
import com.rockcent.model.ContourMap;
import com.rockcent.model.HomepageBO;
import com.rockcent.model.MessageBO;
import com.rockcent.model.Topics;
import com.umeng.analytics.MobclickAgent;
import com.xysq.adapter.HomepageAdapter;
import com.xysq.lemon.R;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.LoadMoreListView;
import com.xysq.widget.XYBannerHelper;
import com.xysq.widget.XYBannerInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;

public class IndexActivity extends BaseActivity implements XYBannerHelper.OnItemClickListener, AdapterView.OnItemClickListener, View.OnClickListener {

    ArrayList<XYBannerInfo> infos;
    private XYBannerHelper banner;
    private ArrayList<String[]> picUrl;
    long exitTime = 0;
    @InjectView(R.id.list_homepage)
    com.xysq.widget.LoadMoreListView homepageList;
    @InjectView(R.id.layout_header)
    LinearLayout headerLayout;
    @InjectView(R.id.llayout_header_bar)
    LinearLayout inputLayout;
    @InjectView(R.id.img_input_mask)
    ImageView inputMaskImg;
    @InjectView(R.id.layout_youcai)
    LinearLayout youcaiLayout;
    @InjectView(R.id.layout_youhuo)
    LinearLayout youhuoLayout;

    @InjectView(R.id.ibtn_msg)
    ImageButton msgIbtn;
    @InjectView(R.id.btn_search)
    Button searchBtn;
    List<ContourMap> contourMap;

    Rect staticRect = new Rect();
    Rect moveRect = new Rect();
    int yStatic;
    int yMovePosition;
    int yMove;
    boolean firstActive = true;
    ArrayList<HomepageBO> homepageBOList;
    HomepageAdapter homepageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        if(UseUtil.detectNetwork(this)) {
            initViewAndData();
            loadData();
        }else {
            ToastUtil.showShort(this, "没有可用的网络，请连接网络后重试");
        }
    }

    private void loadData() {
        getContourMap();
        loadTopics();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("首页");
        MobclickAgent.onResume(this);
        getMessage();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("首页");
        MobclickAgent.onPause(this);
    }

    //获取站内信
    private void getMessage() {
        if (TextUtils.isEmpty(UserInfoKeeper.readPhoneNumber(this))) {
            msgIbtn.setImageResource(R.drawable.ic_header_msg_normal);
        } else {
            appAction.queryInmessage(UserInfoKeeper.readPhoneNumber(this), currentPage, PAGE_SIZE, "2", new CallbackListener<List<MessageBO>>() {
                @Override
                public void onSuccess(List<MessageBO> data) {
                    if (data.size() > 0) {
                        msgIbtn.setImageResource(R.drawable.ic_header_msg_has);
                    } else {
                        msgIbtn.setImageResource(R.drawable.ic_header_msg_normal);
                    }
                }

                @Override
                public void onFailure(String errorCode, String message) {
                }
            });
        }
    }

    private void loadTopics() {
        homepageBOList.clear();
        appAction.getTopics(1, 20, "1", new CallbackListener<List<Topics>>() {
            @Override
            public void onSuccess(List<Topics> data) {
                homepageAdapter.setItems(data);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e("+++++为什么专题获取失败", message);
                ToastUtil.showLong(IndexActivity.this, R.string.toast_get_topics_fail);
            }
        });
    }

    private void initViewAndData() {
        contourMap = new ArrayList<>();
        int screenWidth = UseUtil.getScreenWidth(this);
        youcaiLayout.setOnClickListener(this);
        youhuoLayout.setOnClickListener(this);
        msgIbtn.setOnClickListener(this);
        searchBtn.setOnClickListener(this);
        homepageList.setOnItemClickListener(this);
        homepageBOList = new ArrayList<HomepageBO>();
        homepageAdapter = new HomepageAdapter(this, appAction);//SaleMeActivity.this, homepageBOList, imageLoader
        final View header = View.inflate(IndexActivity.this, R.layout.stick_header, null);//这是头部内容
        header.setMinimumHeight(screenWidth / 5 * 3);
        homepageList.addHeaderView(header);//添加头部

        final View mask = View.inflate(IndexActivity.this, R.layout.stick_action, null);
        LinearLayout youcaiLayout = (LinearLayout)mask.findViewById(R.id.layout_youcai);
        LinearLayout youhuoLayout = (LinearLayout)mask.findViewById(R.id.layout_youhuo);
        youcaiLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO
                Intent intent = new Intent(IndexActivity.this, TalentActivity.class);
                startActivity(intent);
            }
        });
        youhuoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO
                Intent intent = new Intent(IndexActivity.this, MarketActivity.class);
                intent.putExtra(OtherTopicsActivity.TITLE, "有货");
                startActivity(intent);
            }
        });

        homepageList.addHeaderView(mask);//ListView条目中的悬浮部分 添加到头部
        homepageList.setOverScrollMode(View.OVER_SCROLL_NEVER);
        homepageList.setDivider(null);
        homepageList.setAdapter(homepageAdapter);
        yMovePosition = screenWidth / 5 * 3 + 50;
        homepageList.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                new LoadDataTask().execute();
            }
        });

        homepageList.setOnScrollListener(new AbsListView.OnScrollListener() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }


            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                mask.getGlobalVisibleRect(moveRect);//mask是会移动的header2,对应move
                inputLayout.getGlobalVisibleRect(staticRect);

                yMove = moveRect.top;
                yStatic = staticRect.bottom;

                if (yMove >= yStatic && yMove <= yMovePosition) {
                    headerLayout.setVisibility(View.GONE);
                    float alPha = 1 - (float) (yMove - yStatic) / (yMovePosition - yStatic);
                    inputMaskImg.setAlpha(alPha);
                } else if (yMove < yStatic) {
                    headerLayout.setVisibility(View.VISIBLE);
                    float alPha = 1;
                    inputMaskImg.setAlpha(alPha);
                }
            }
        });
    }

    private void getContourMap() {
        appAction.getContour(new CallbackListener<List<ContourMap>>() {
            @Override
            public void onSuccess(List<ContourMap> data) {
                if (data != null) {
                    contourMap = data;
                    int size = data.size();
                    picUrl = new ArrayList<>();
                    for (int i = 0; i < size; i++) {
                        String singleUrl[] = new String[2];
                        singleUrl[0] = "";
                        singleUrl[1] = PropertiesUtil.getImageServer() + data.get(i).getImgurl();
                        picUrl.add(singleUrl);
                    }
                    processPicUrl(picUrl);

                }
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(IndexActivity.this, "获取广告栏信息失败");
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {  //System.currentTimeMillis()无论何时调用，肯定大于2000
                ToastUtil.showLong(IndexActivity.this, getResources().getString(R.string.toast_more_time_exit));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击事件回调
     *
     * @param index : 被点击的图片列表位置
     * @param v
     */
    @Override
    public void onItemClick(int index, View v) {
        Log.e("++++什么鬼", "什么鬼啊");
        if (TextUtils.isEmpty(UserInfoKeeper.readPhoneNumber(this)) & contourMap.get(index).getUrl().equals(WebViewActivity.GIFT)) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            Intent intent = new Intent(IndexActivity.this, WebViewActivity.class);
            intent.putExtra("h5Url", contourMap.get(index).getUrl());
            startActivity(intent);
        }
    }

    private void initBanner() {
        banner = new XYBannerHelper(this);
        banner.setBannerInfo(infos);
        banner.startAutoRoll();
        banner.setOnItemClickCallback(this);
    }

    private void processPicUrl(ArrayList<String[]> picUrl) {
        int size = picUrl.size();
        infos = new ArrayList<XYBannerInfo>();
        for (int i = 0; i < size; i++) {
            String[] singleUrl = picUrl.get(i);
            infos.add(new XYBannerInfo(singleUrl[0], singleUrl[1]));
        }
        initBanner();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Topics topics = (Topics) homepageAdapter.getItem(i - 2);
        appAction.behavior(topics.getUuid(), UserInfoKeeper.readCustomerId(IndexActivity.this), "1", new CallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
            }

            @Override
            public void onFailure(String errorCode, String message) {
            }
        });
        Intent intent = new Intent(IndexActivity.this, TicketsListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(TicketsListActivity.TOPICS, topics);
        intent.putExtra(TicketsListActivity.BUNDLE_TOPICS, bundle);
        startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        if(view == youcaiLayout){
            //TODO
//            Intent intent = new Intent(this, CustomerCouponActivity.class);
//            intent.putExtra(OtherTopicsActivity.TITLE, "有才");
            Intent intent = new Intent(this, TalentActivity.class);
            startActivity(intent);
        }
        if(view == youhuoLayout){
            Intent intent = new Intent(this, MarketActivity.class);
            intent.putExtra(OtherTopicsActivity.TITLE, "有货");
            startActivity(intent);
        }
        if (view == msgIbtn) {
            String phone = UserInfoKeeper.readPhoneNumber(this);
            if (TextUtils.isEmpty(phone)) {
                startActivity(new Intent(this, LoginActivity.class));
            } else {
                startActivity(new Intent(this, MessageListActivity.class));
            }
        }
        if (view == searchBtn) {
            startActivity(new Intent(this, SearchActivity.class));
        }
    }

    private class LoadDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            if (isCancelled()) {
                return null;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            homepageAdapter.notifyDataSetChanged();
            homepageList.onLoadMoreComplete();
            super.onPostExecute(result);
        }

        @Override
        protected void onCancelled() {
            homepageList.onLoadMoreComplete();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (banner != null) {
            banner.destroyHelper();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (banner != null && firstActive == false) {
            banner.startAutoRoll();
        }
        firstActive = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (banner != null) {
            banner.stopAutoRoll();
        }
    }
}
